package com.TeaManage.servlet;

import com.TeaManage.bean.Supplier;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@WebServlet(name = "SupplierServlet", urlPatterns = "/SupplierServlet")
public class SupplierServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            // 添加供应商
            String supplierName = request.getParameter("supplier_name");
            String phone = request.getParameter("phone");
            String email = request.getParameter("email");
            String address = request.getParameter("address");
            String statusStr = request.getParameter("status");
            
            // 验证必填字段
            if (supplierName == null || supplierName.trim().isEmpty() ||
                phone == null || phone.trim().isEmpty()) {
                request.setAttribute("error", "供应商名称和电话不能为空");
                request.getRequestDispatcher("/views/supplier/addSupplier.jsp").forward(request, response);
                return;
            }
            
            // 验证电话格式
            if (!isValidPhone(phone)) {
                request.setAttribute("error", "电话格式不正确");
                request.getRequestDispatcher("/views/supplier/addSupplier.jsp").forward(request, response);
                return;
            }
            
            // 验证邮箱格式
            if (email != null && !email.trim().isEmpty() && !isValidEmail(email)) {
                request.setAttribute("error", "邮箱格式不正确");
                request.getRequestDispatcher("/views/supplier/addSupplier.jsp").forward(request, response);
                return;
            }
            
            // 检查供应商名称是否已存在
            String checkSql = "SELECT COUNT(*) FROM supplier WHERE supplier_name = ?";
            int count = GokJDBCUtil.queryForCount(checkSql, supplierName);
            if (count > 0) {
                request.setAttribute("error", "供应商名称已存在");
                request.getRequestDispatcher("/views/supplier/addSupplier.jsp").forward(request, response);
                return;
            }
            
            // 检查电话是否已存在
            String checkPhoneSql = "SELECT COUNT(*) FROM supplier WHERE phone = ?";
            int phoneCount = GokJDBCUtil.queryForCount(checkPhoneSql, phone);
            if (phoneCount > 0) {
                request.setAttribute("error", "电话号码已存在");
                request.getRequestDispatcher("/views/supplier/addSupplier.jsp").forward(request, response);
                return;
            }
            
            int status = statusStr != null ? Integer.parseInt(statusStr) : 1;
            
            String sql = "INSERT INTO supplier(supplier_name, phone, email, address, status) VALUES(?, ?, ?, ?, ?)";
            int result = GokJDBCUtil.update(sql, supplierName, phone, email, address, status);
            if (result > 0) {
                response.sendRedirect("SupplierServlet");
            }
            
        } else if ("toAdd".equals(action)) {
            // 跳转到新增页面
            request.getRequestDispatcher("/views/supplier/addSupplier.jsp").forward(request, response);
            
        } else if ("deleteById".equals(action)) {
            // 删除供应商
            int id = Integer.parseInt(request.getParameter("id"));
            
            // 检查是否有采购记录使用此供应商
            String checkSql = "SELECT COUNT(*) FROM purchase WHERE supplier_id = ?";
            int purchaseCount = GokJDBCUtil.queryForCount(checkSql, id);
            if (purchaseCount > 0) {
                request.setAttribute("error", "该供应商还有采购记录，无法删除");
                loadSupplierList(request, response);
                return;
            }
            
            String sql = "DELETE FROM supplier WHERE supplier_id = ?";
            int result = GokJDBCUtil.update(sql, id);
            response.sendRedirect("SupplierServlet");
            
        } else if ("findById".equals(action)) {
            // 查找供应商用于编辑
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "SELECT * FROM supplier WHERE supplier_id = ?";
            Supplier supplier = GokJDBCUtil.queryForObject(sql, Supplier.class, id);
            request.setAttribute("supplier", supplier);
            request.getRequestDispatcher("/views/supplier/editSupplier.jsp").forward(request, response);
            
        } else if ("update".equals(action)) {
            // 更新供应商
            int id = Integer.parseInt(request.getParameter("supplier_id"));
            String supplierName = request.getParameter("supplier_name");
            String phone = request.getParameter("phone");
            String email = request.getParameter("email");
            String address = request.getParameter("address");
            String statusStr = request.getParameter("status");
            
            // 验证必填字段
            if (supplierName == null || supplierName.trim().isEmpty() ||
                phone == null || phone.trim().isEmpty()) {
                request.setAttribute("error", "供应商名称和电话不能为空");
                Supplier supplier = GokJDBCUtil.queryForObject("SELECT * FROM supplier WHERE supplier_id = ?", Supplier.class, id);
                request.setAttribute("supplier", supplier);
                request.getRequestDispatcher("/views/supplier/editSupplier.jsp").forward(request, response);
                return;
            }
            
            // 验证电话格式
            if (!isValidPhone(phone)) {
                request.setAttribute("error", "电话格式不正确");
                Supplier supplier = GokJDBCUtil.queryForObject("SELECT * FROM supplier WHERE supplier_id = ?", Supplier.class, id);
                request.setAttribute("supplier", supplier);
                request.getRequestDispatcher("/views/supplier/editSupplier.jsp").forward(request, response);
                return;
            }
            
            // 验证邮箱格式
            if (email != null && !email.trim().isEmpty() && !isValidEmail(email)) {
                request.setAttribute("error", "邮箱格式不正确");
                Supplier supplier = GokJDBCUtil.queryForObject("SELECT * FROM supplier WHERE supplier_id = ?", Supplier.class, id);
                request.setAttribute("supplier", supplier);
                request.getRequestDispatcher("/views/supplier/editSupplier.jsp").forward(request, response);
                return;
            }
            
            // 检查供应商名称是否已存在（排除当前供应商）
            String checkSql = "SELECT COUNT(*) FROM supplier WHERE supplier_name = ? AND supplier_id != ?";
            int count = GokJDBCUtil.queryForCount(checkSql, supplierName, id);
            if (count > 0) {
                request.setAttribute("error", "供应商名称已存在");
                Supplier supplier = GokJDBCUtil.queryForObject("SELECT * FROM supplier WHERE supplier_id = ?", Supplier.class, id);
                request.setAttribute("supplier", supplier);
                request.getRequestDispatcher("/views/supplier/editSupplier.jsp").forward(request, response);
                return;
            }
            
            // 检查电话是否已存在（排除当前供应商）
            String checkPhoneSql = "SELECT COUNT(*) FROM supplier WHERE phone = ? AND supplier_id != ?";
            int phoneCount = GokJDBCUtil.queryForCount(checkPhoneSql, phone, id);
            if (phoneCount > 0) {
                request.setAttribute("error", "电话号码已存在");
                Supplier supplier = GokJDBCUtil.queryForObject("SELECT * FROM supplier WHERE supplier_id = ?", Supplier.class, id);
                request.setAttribute("supplier", supplier);
                request.getRequestDispatcher("/views/supplier/editSupplier.jsp").forward(request, response);
                return;
            }
            
            int status = statusStr != null ? Integer.parseInt(statusStr) : 1;
            
            String sql = "UPDATE supplier SET supplier_name = ?, phone = ?, email = ?, address = ?, status = ? WHERE supplier_id = ?";
            int result = GokJDBCUtil.update(sql, supplierName, phone, email, address, status, id);
            if (result > 0) {
                response.sendRedirect("SupplierServlet");
            }
            
        } else if ("search".equals(action)) {
            // 搜索供应商
            String name = request.getParameter("name");
            String phone = request.getParameter("phone");
            String statusStr = request.getParameter("status");
            
            // 分页参数
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT * FROM supplier WHERE 1=1");
            List<Object> params = new ArrayList<>();
            
            if (name != null && !name.trim().isEmpty()) {
                sql.append(" AND supplier_name LIKE ?");
                params.add("%" + name + "%");
            }
            if (phone != null && !phone.trim().isEmpty()) {
                sql.append(" AND phone LIKE ?");
                params.add("%" + phone + "%");
            }
            if (statusStr != null && !statusStr.trim().isEmpty()) {
                sql.append(" AND status = ?");
                params.add(Integer.parseInt(statusStr));
            }
            
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            
            // 添加分页
            sql.append(" ORDER BY supplier_id DESC LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            
            List<Supplier> supplierList = GokJDBCUtil.queryAll(sql.toString(), Supplier.class, params.toArray());
            
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            
            // 返回结果
            request.setAttribute("supplierList", supplierList);
            request.setAttribute("name", name);
            request.setAttribute("phone", phone);
            request.setAttribute("status", statusStr);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/supplier/supplier.jsp").forward(request, response);
            
        } else {
            // 默认显示供应商列表
            loadSupplierList(request, response);
        }
    }
    
    private void loadSupplierList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            page = 1;
            pageSize = 10;
        }
        
        // 查询总数
        String countSql = "SELECT COUNT(*) FROM supplier";
        int total = GokJDBCUtil.queryForCount(countSql);
        
        // 查询数据
        String sql = "SELECT * FROM supplier ORDER BY supplier_id DESC LIMIT ?, ?";
        List<Supplier> supplierList = GokJDBCUtil.queryAll(sql, Supplier.class, (page-1)*pageSize, pageSize);
        
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        
        request.setAttribute("supplierList", supplierList);
        request.setAttribute("page", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("views/supplier/supplier.jsp").forward(request, response);
    }
    
    private boolean isValidPhone(String phone) {
        // 简单的电话号码验证：11位数字或带区号的固定电话
        String phonePattern = "^(1[3-9]\\d{9}|0\\d{2,3}-?\\d{7,8})$";
        return Pattern.matches(phonePattern, phone);
    }
    
    private boolean isValidEmail(String email) {
        String emailPattern = "^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$";
        return Pattern.matches(emailPattern, email);
    }
}
